package handler

import (
	"net/http"

	"github.com/gin-gonic/gin"

	"plastic-company/internal/model"
)

// GetProducts 获取所有产品
func GetProducts(c *gin.Context) {
	var products []model.Product
	result := db.Find(&products)

	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, model.APIResponse{
			Success: false,
			Message: "获取产品失败",
		})
		return
	}

	c.JSON(http.StatusOK, model.APIResponse{
		Success: true,
		Data:    products,
	})
}

// GetProduct 获取单个产品
func GetProduct(c *gin.Context) {
	id := c.Param("id")

	var product model.Product
	result := db.First(&product, id)

	if result.Error != nil {
		if result.Error.Error() == "record not found" {
			c.JSON(http.StatusNotFound, model.APIResponse{
				Success: false,
				Message: "产品不存在",
			})
		} else {
			c.JSON(http.StatusInternalServerError, model.APIResponse{
				Success: false,
				Message: "获取产品失败",
			})
		}
		return
	}

	c.JSON(http.StatusOK, model.APIResponse{
		Success: true,
		Data:    product,
	})
}

// CreateProduct 创建产品
func CreateProduct(c *gin.Context) {
	var product model.Product

	if err := c.ShouldBindJSON(&product); err != nil {
		c.JSON(http.StatusBadRequest, model.APIResponse{
			Success: false,
			Message: "请求参数错误",
		})
		return
	}

	result := db.Create(&product)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, model.APIResponse{
			Success: false,
			Message: "创建产品失败",
		})
		return
	}

	c.JSON(http.StatusCreated, model.APIResponse{
		Success: true,
		Message: "创建产品成功",
		Data:    product,
	})
}

// UpdateProduct 更新产品
func UpdateProduct(c *gin.Context) {
	id := c.Param("id")

	var product model.Product
	if err := c.ShouldBindJSON(&product); err != nil {
		c.JSON(http.StatusBadRequest, model.APIResponse{
			Success: false,
			Message: "请求参数错误",
		})
		return
	}

	result := db.Model(&product).Where("id = ?", id).Updates(&product)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, model.APIResponse{
			Success: false,
			Message: "更新产品失败",
		})
		return
	}

	c.JSON(http.StatusOK, model.APIResponse{
		Success: true,
		Message: "更新产品成功",
		Data:    product,
	})
}

// DeleteProduct 删除产品
func DeleteProduct(c *gin.Context) {
	id := c.Param("id")

	result := db.Delete(&model.Product{}, id)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, model.APIResponse{
			Success: false,
			Message: "删除产品失败",
		})
		return
	}

	c.JSON(http.StatusOK, model.APIResponse{
		Success: true,
		Message: "删除产品成功",
	})
}
